/*
 * @Author: czy
 * @Date: 2021-05-30 21:29:03
 * @LastEditTime: 2021-05-30 21:53:44
 */
#include "string.h"

#include "api/system.h"

#define PROPORTION 0.8

static unsigned long KMEMHandler = 0;
static unsigned long UMEMHandler = 0;

static void initMEM(void)
{
    if (KMEMHandler == 0 || UMEMHandler == 0)
    {
        unsigned long memStart = getMemStart();
        unsigned long memSize = getMemSize();
        unsigned long size = (memSize * PROPORTION) / 2;
        unsigned long memHandler = eFPartitionInit(memStart, size, 2);
        KMEMHandler = dPartitionInit(eFPartitionAlloc(memHandler), size);
        UMEMHandler = dPartitionInit(eFPartitionAlloc(memHandler), size);
    }
}

unsigned long kmalloc(unsigned long size)
{
    initMEM();
    return dPartitionAlloc(KMEMHandler, size);
}

unsigned long kfree(unsigned long start)
{
    initMEM();
    return dPartitionFree(KMEMHandler, start);
}

unsigned long malloc(unsigned long size)
{
    initMEM();
    return dPartitionAlloc(UMEMHandler, size);
}

unsigned long free(unsigned long start)
{
    initMEM();
    return dPartitionFree(UMEMHandler, start);
}

unsigned long calloc(int nitems, unsigned long size)
{
    initMEM();
    unsigned long totalSize = nitems * size;
    unsigned long handler = dPartitionAlloc(UMEMHandler, totalSize);
    memset((void *)handler, '\0', totalSize);
    return handler;
}

unsigned long realloc(unsigned long start, unsigned long size)
{
    initMEM();
    dPartitionFree(UMEMHandler, start);
    return dPartitionAlloc(UMEMHandler, size);
}